# coding:utf-8

from databaseHandler import *
from datetime import datetime
from .nodeModel import *
from .userModel import *
from .categoryModel import *

# 节点的数据库模型


class Node(db.Entity):
    nodeName = Required(str)  # 节点名称
    nodeDescription = Optional(str)  # 节点介绍
    createdTime = Required(datetime)  # 节点创建时间
    nodeApplicant = Required('User')  # 节点申请人
    nodeManager = Required('User')  # 节点管理者
    relatedArticles = Set('Article')  # 节点包含的帖子
    nodeFavorited = Set('User', reverse='favoritedNodes')  # 收藏节点的用户
    belongCategory = Required('Category', reverse='nodes')  # 节点归属的论坛版块


# 新建节点
@db_session
def newNode(nodeName, nodeDescription, nodeApplicant):
    if checkNode(nodeName) is False:
        Node(nodeName=nodeName,
             nodeDescription=nodeDescription,
             nodeApplicant=nodeApplicant,
             nodeManager=nodeApplicant,
             createdTime=datetime.now())
        return True
    else:
        return False

# 通过名称获得节点


@db_session
def getNodeByName(nodeName):
    node = Node.get(nodeName=nodeName)
    return node

# 更改节点鹳狸猿


@db_session
def changeNodeManager(nodeName, User):
    node = getNodeByName(nodeName)
    node.nodeManager = User
    return True

# 检测检点是否存在


@db_session
def checkNode(nodeName):
    return Node.exists(nodeName=nodeName)

# 获得所有节点


@db_session
def getAllNodes():
    return Node.select()
